package app.controller;

import app.book.BookDao;
import app.util.Path;
import app.util.Property;
import app.util.RequestUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import spark.ModelAndView;
import spark.Request;
import spark.Response;
import spark.Route;
import spark.template.mustache.MustacheTemplateEngine;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StatisticController {

    private final static Logger logger = LoggerFactory.getLogger(StatisticController.class);

    public static Route serveStatisticPage = (Request req, Response resp) -> {
        logger.info("request page: /statistic");
        Map<String, Object> model = new HashMap<>();
        model.put("daterangestart", LocalDate.of(LocalDate.now().getYear(), 1, 1).format(DateTimeFormatter.ofPattern("yyyyMMdd")));
        model.put("daterangeend", LocalDate.of(LocalDate.now().getYear(), LocalDate.MAX.getMonth(), LocalDate.MAX.getDayOfMonth()).format(DateTimeFormatter.ofPattern("yyyyMMdd")));
        MustacheTemplateEngine engine = new MustacheTemplateEngine();
        ModelAndView mav = new ModelAndView(model, Path.Template.STATISTIC);
        return engine.render(mav);
    };

    public static Route serveSTResultRequest = (Request req, Response resp) -> {
        String dateStart = RequestUtil.getParamDateStart(req);
        String dateEnd = RequestUtil.getParamDateEnd(req);
        logger.info(String.format("statistic from %s to %s", dateStart, dateEnd));
        List<Property> props = BookDao.statisticBookByDate(dateStart, dateEnd);
        resp.type("application/json");
        ObjectMapper mapper = new ObjectMapper();
        logger.info("statistic results as: ");
        for (Property p: props) {
            logger.info(String.format("\t%s: %s", p.getKey(), p.getValue()));
        }
        return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(props);
    };

    public static Route serveSTResultBooksByMonth = (Request req, Response resp) -> {
        List<Integer> books = BookDao.getBooksByMonth();
        logger.info("request books permonth: ");
        logger.info("\t"+books.toString());
        ObjectMapper mapper = new ObjectMapper();
        resp.type("application/json");
        return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(books);
    };
}
